#!/usr/bin/ruby
#
# require ruby 1.6 ~ 1.8
#
# Ver. 1.1.7
# Created: 2005-04-12
# Modified: 2007-01-27
# Play, Modify and Share!
# HH
#


def fetch_1_6(uri_str, limit=10)
  require 'net/http'
  require 'uri'
  
  raise RedirectTooDeep if limit.zero?
  
  u = URI.parse(uri_str)
  
  r = nil
  body = nil
  
  Net::HTTP.start(u.host) do |h|
    r, body = h.get(u.request_uri)
  end
  
  return [r, body]

rescue Net::ProtoRetriableError => err
	fetch_1_6(err.response['location'], limit-1)
end

def fetch_1_8(uri_str, limit=10)
  require 'net/http'
  require 'uri'
  
  raise RedirectTooDeep if limit.zero?
  
  response = Net::HTTP.get_response(URI.parse(uri_str))

  case response
  when Net::HTTPSuccess
    response
  when Net::HTTPRedirection
    fetch_1_8(response['location'], limit-1)
  else
    response.error!
  end
end

def get_body(uri_str)
	
	if RUBY_VERSION >= "1.8"
	  r = fetch_1_8(uri_str)
	  body = r.body
	else
	  r, body = fetch_1_6(uri_str)
	end
	
	#puts body
	body
end

def extract_mms(body)
	#puts body
	#playerURL = body.scan(/Player\.URL = \"([^\"]*?)\"/m)
	playerURL = body.scan(/setMovieFile\(\"([^\"]*?)\"/m)
	#p playerURL
  
	m = nil
	unless playerURL.empty?
	  uri = playerURL[0][0]
		body = get_body(uri)
		body.each do |line|
			if line =~ /href=\"(.*)\"/
				m = $1
				break
			end
		end
	end
	
	m
end


#
# Error types.
#
class Error < StandardError; end
class ArgvError < Error; end
class NoMms < Error; end
class RedirectTooDeep < Error; end

begin

	# check argv
	if ARGV.length != 1
		raise ArgvError
	end
	
	uri = ARGV[0]
	uri = uri.sub(/player\.jsp/, "player_ff.jsp")
	body = get_body(uri)
	if mms = extract_mms(body)
		puts mms
	else
		raise NoMms
	end
rescue RedirectTooDeep
	$stderr.print("http redirect too deep.\n")
	exit(3)	
rescue NoMms
	$stderr.print("Can't find mms on this link.\n")
	exit(2)	
rescue ArgvError
	print("Please run this script from the associated AppleScript \"get_mms\".\n")
	exit(1)
end
